package fun.ticsmyc.multiThread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ticsmyc
 * @date 2020-12-10 10:55
 */
public class 三线程Lock {

    public static void main(String[] args) {

        ReentrantLock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();
        Runnable task1 = ()->{
            while(true){
                try {
                    lock.lock();
                    System.out.println("线程1"+" "+Thread.currentThread().getName());
                    condition2.signal();
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }

        };
        Runnable task2 = ()->{
            while(true){
                try {
                    lock.lock();
                    System.out.println("线程2"+" "+Thread.currentThread().getName());
                    condition3.signal();
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }

        };
        Runnable task3 = ()->{
            while(true){
                try {
                    lock.lock();
                    System.out.println("线程3"+" "+Thread.currentThread().getName());
                    condition1.signal();
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(task1);
        executorService.submit(task2);
        executorService.submit(task3);
    }
}
